package com.google.code.jam.util;

import static  java.lang.System.out;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;



/**
 * 
 * @author spaida
 *
 */
public class FileHelper {

	/**
	 * 
	 * @param fileName
	 * @return
	 * @throws Exception
	 */
	public static String readFile(String fileName)throws Exception{
		out.println("Reading Mapping file.");
	  BufferedReader buff= null;
	  try{
		FileReader freader=new FileReader(fileName);
	    buff=new BufferedReader(freader);
	    StringBuffer msg=new StringBuffer();
	    String line=null;
	    while((line=buff.readLine())!=null){
	           msg.append(line+"\n");
	    }
	    buff.close();
	    return msg.toString();
      }finally{
    	  if(buff!=null)
    		  buff.close();
      }
	}
	
	/**
	 * 
	 * @param outFile
	 * @param content
	 * @throws Exception
	 */
	public static void writeFile(String outFile, String content) throws Exception {
		Writer writer = null;
		try{
		  if(outFile==null || content==null){
			  out.println("Noting to writed outFile:"+outFile);
			  return;
		  }
		  writer = new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8");
	    //java.io.FileWriter writer = new java.io.FileWriter(outFile);
		  writer.write(content);
		  writer.flush();
		  writer.close();
		}catch(Exception e){	
			out.println("Problems writing "+outFile);
		}finally{
			if(writer!=null)
				writer.close();
		}
	}
	
	
	/**
	 * 
	 * @param resourceLocation
	 * @return
	 */
	public static String getResourceFromJar(String resourceLocation){
		try{ 
			InputStream is =FileHelper.class.getResourceAsStream(resourceLocation);
			if(is==null){
				return null;
			}

			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			StringBuilder sb = new StringBuilder();
			String line = null;

			while ((line = br.readLine()) != null) {
				sb.append(line + "\n");
			}
			br.close();
			return sb.toString();
		}catch(Exception e){
			return null;
		}
	}
	
}
